package pe.gob.osinergmin.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;

import com.google.android.gms.maps.GoogleMap;

public class PuntoControlMapStateManager {

    private static final String LONGITUDE_START = "longitude_start";
    private static final String LATITUDE_START = "latitude_start";
    private static final String DATE_START = "date_start";

    private static final String LONGITUDE_END = "longitude_end";
    private static final String LATITUDE_END = "latitude_end";
    private static final String DATE_END = "date_end";

    private static final String MAPTYPE = "MAPTYPE";

    private static final String PREFS_NAME ="mapState";

    private SharedPreferences mapStatePrefs;

    public PuntoControlMapStateManager(Context context) {
        mapStatePrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    }

    public void saveMapState(GoogleMap map, Location me_position, Location truck_position) {
        SharedPreferences.Editor editor = mapStatePrefs.edit();

        // My Position
        editor.putFloat(LATITUDE_START, (float) me_position.getLatitude());
        editor.putFloat(LONGITUDE_START, (float) me_position.getLongitude());
        editor.putLong(DATE_START, me_position.getTime());

        // Truck Position
        editor.putFloat(LATITUDE_END, (float) truck_position.getLatitude());
        editor.putFloat(LONGITUDE_END, (float) truck_position.getLongitude());
        editor.putLong(DATE_END, truck_position.getTime());

        editor.putInt(MAPTYPE, map.getMapType());

        editor.commit();
    }

    public Location getMePosition() {
        double latitude = mapStatePrefs.getFloat(LATITUDE_START, 0);
        if (latitude == 0) {
            return null;
        }
        double longitude = mapStatePrefs.getFloat(LONGITUDE_START, 0);
        long date_start = mapStatePrefs.getLong(DATE_START, 0);

        Location position = new  Location(PuntoControlConstants.LOCATION_DUMMY_PROVIDER);
        position.setLatitude(latitude);
        position.setLongitude(longitude);
        position.setTime(date_start);

        return position;
    }

    public Location getTruckPosition() {
        double latitude = mapStatePrefs.getFloat(LATITUDE_END, 0);
        if (latitude == 0) {
            return null;
        }
        double longitude = mapStatePrefs.getFloat(LONGITUDE_END, 0);
        long date_start = mapStatePrefs.getLong(DATE_END, 0);

        Location position = new  Location(PuntoControlConstants.LOCATION_DUMMY_PROVIDER);
        position.setLatitude(latitude);
        position.setLongitude(longitude);
        position.setTime(date_start);

        return position;
    }

    //	This is part of the answer to the code challenge
    public int getSavedMapType() {
        return mapStatePrefs.getInt(MAPTYPE, GoogleMap.MAP_TYPE_NORMAL);
    }
}
